﻿module Runner {
    enum battleState { onGoing, success, fail };
    export class Battle extends Phaser.Group {
        backgroundSprite: BattleBackground;
        heroSprite: Hero;
        enemies: Enemy[];
        combatLog: TextWindow;
        stateOf: battleState = battleState.onGoing;

        constructor(game: Phaser.Game, hero: Runner.Hero, enemies: Runner.Enemy[]) {
            super(game, null, 'Battle', true);
            
            this.enemies = [new Enemy(this.game, 0, 0, enemies[0].key.toString(), null, null, null, false)];

            this.create();
        }

        create() {
            this.backgroundSprite = new BattleBackground(this.game);
            this.add(this.backgroundSprite);

            this.heroSprite = new Hero(this.game, 0, 0, false);

            var screenSubset = 1.4;
            var enemySpacing = (this.game.width / screenSubset) / (this.enemies.length + 1);

            for (var e = 0; e < this.enemies.length; e++) {
                //this.enemies[e].bringToTop();
                
                this.enemies[e].scale.x = this.enemies[e].scale.y = 2;
                this.enemies[e].x = (enemySpacing * (e + 1)) + (this.game.width - (this.game.width / screenSubset));
                this.enemies[e].y = this.game.height / 3;
                this.enemies[e].animations.play('shoot_backward');
                this.enemies[e].scale.x *= -1;
                this.add(this.enemies[e]);

                buildHitPointBar(this.enemies[e]);

                this.enemies[e].events.onKilled.add(function (element) {
                    var index = this.enemies.indexOf(element);
                    this.enemies.splice(index, 1);

                    element.body = null;
                    element.destroy();

                    if (this.enemies.length <= 0) {
                        this.stateOf = battleState.success;
                    }
                }, this);
            }

            this.heroSprite.scale.x = this.heroSprite.scale.y = 2;
            this.heroSprite.x = this.game.width - (this.game.width / 1.2);
            this.heroSprite.y = this.game.height * 0.75;

            this.heroSprite.animations.stop();
            this.heroSprite.animations.frame = 0;
            this.add(this.heroSprite);

            buildHitPointBar(this.heroSprite);

            this.combatLog = new TextWindow(this.game, 'Combat Log', (this.game.width / 2) + 50, this.game.height * 0.70, 300, 150);
            this.combatLog.writeWindowText('Battle has Begun!');
            this.onAnswer(true,this.game);
        }

        onAnswer(answer: boolean, battle: Phaser.Game) {
            if (answer) {
                //poseQuestion(battle, this);
            }
        }

        update() {
            this.backgroundSprite.update();
            if (this.stateOf == battleState.onGoing) {

            }
        }
    }
}